#!/bin/bash
# Deployment script for Buyu Application

set -e  # Exit on error

echo "========================================="
echo "Buyu Application Deployment Script"
echo "========================================="

# Configuration
APP_DIR="/var/www/buyu"
BACKEND_DIR="$APP_DIR/backend"
VENV_DIR="$APP_DIR/venv"
LOG_DIR="/var/log/buyu"
RUN_DIR="/var/run/buyu"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    log_error "Please run as root or with sudo"
    exit 1
fi

# Step 1: Create directories
log_info "Creating directories..."
mkdir -p $APP_DIR
mkdir -p $LOG_DIR
mkdir -p $RUN_DIR
mkdir -p $BACKEND_DIR/static/music

# Step 2: Set up Python virtual environment
log_info "Setting up Python virtual environment..."
if [ ! -d "$VENV_DIR" ]; then
    python3 -m venv $VENV_DIR
fi
source $VENV_DIR/bin/activate

# Step 3: Install dependencies
log_info "Installing Python dependencies..."
cd $BACKEND_DIR
pip install --upgrade pip
pip install -r requirements.txt
pip install gunicorn  # Add gunicorn for production

# Step 4: Set up environment file
log_info "Checking environment configuration..."
if [ ! -f "$BACKEND_DIR/.env.production" ]; then
    log_warn ".env.production not found. Copying from example..."
    cp $BACKEND_DIR/.env.production.example $BACKEND_DIR/.env.production
    log_warn "Please edit .env.production with actual values!"
fi

# Step 5: Initialize database
log_info "Initializing database..."
read -p "Have you created the MySQL database? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    log_info "Running database migrations..."
    export FLASK_APP=run.py
    export FLASK_ENV=production
    flask db upgrade 2>/dev/null || log_warn "No migrations found, tables will be created on first run"
else
    log_warn "Please create the database using deployment/mysql_init.sql"
fi

# Step 6: Set permissions
log_info "Setting permissions..."
chown -R www-data:www-data $APP_DIR
chown -R www-data:www-data $LOG_DIR
chown -R www-data:www-data $RUN_DIR
chmod -R 755 $APP_DIR
chmod -R 755 $LOG_DIR

# Step 7: Install systemd services
log_info "Installing systemd services..."
cp $BACKEND_DIR/deployment/buyu_backend.service /etc/systemd/system/
cp $BACKEND_DIR/deployment/celery_worker.service /etc/systemd/system/
cp $BACKEND_DIR/deployment/celery_beat.service /etc/systemd/system/

systemctl daemon-reload

# Step 8: Configure Nginx
log_info "Configuring Nginx..."
if [ -f "/etc/nginx/sites-available/buyu" ]; then
    log_warn "Nginx config already exists, skipping..."
else
    cp $BACKEND_DIR/deployment/nginx.conf /etc/nginx/sites-available/buyu
    ln -sf /etc/nginx/sites-available/buyu /etc/nginx/sites-enabled/buyu
    log_info "Testing Nginx configuration..."
    nginx -t
fi

# Step 9: Start services
log_info "Starting services..."
read -p "Start services now? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    systemctl enable buyu_backend
    systemctl enable celery_worker
    systemctl enable celery_beat
    
    systemctl start buyu_backend
    systemctl start celery_worker
    systemctl start celery_beat
    systemctl reload nginx
    
    log_info "Services started successfully!"
    
    # Check status
    echo ""
    log_info "Service Status:"
    systemctl status buyu_backend --no-pager -l
    systemctl status celery_worker --no-pager -l
    systemctl status celery_beat --no-pager -l
else
    log_info "Services not started. Start manually with:"
    echo "  systemctl start buyu_backend"
    echo "  systemctl start celery_worker"
    echo "  systemctl start celery_beat"
    echo "  systemctl reload nginx"
fi

echo ""
log_info "========================================="
log_info "Deployment completed!"
log_info "========================================="
log_info "Next steps:"
echo "  1. Edit $BACKEND_DIR/.env.production with actual credentials"
echo "  2. Configure SSL certificates in Nginx"
echo "  3. Set up firewall rules (allow ports 80, 443)"
echo "  4. Configure monitoring and logging"
echo "  5. Test the application"
log_info "========================================="
